package com.youlu.campus.service.kos;

import com.mongodb.client.result.UpdateResult;
import com.youlu.campus.entity.course.entity.KosCoupons;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

/**
 * @author : [dengbo]
 * @className : Coupons
 * @description : [描述说明该类的功能]
 * @createTime : [2022/9/14 17:14]
 */
@Service
@Slf4j
public class KosCouponsService {

    @Autowired
    private MongoTemplate mongoTemplate;

    public KosCoupons getNotUseKosCoupons() {
        KosCoupons coupons = mongoTemplate.findOne(new Query(Criteria.where("status").is(0)), KosCoupons.class);
        return coupons;
    }

    public KosCoupons findByRedeemCode(String redeemCode) {
        KosCoupons coupons = mongoTemplate.findOne(new Query(Criteria.where("redeemCode").is(redeemCode)), KosCoupons.class);
        return coupons;
    }

    public KosCoupons findByUserId(String activityId, String userId) {
        Query query = new Query(Criteria.where("activityId").is(activityId).and("userId").is(userId));
        KosCoupons coupons = mongoTemplate.findOne(query, KosCoupons.class);
        return coupons;
    }

    public boolean bindByRedeemCode(String redeemCode, String userId) {
        Query query = new Query(Criteria.where("redeemCode").is(redeemCode).and("status").is(0));
        Update update = new Update();
        update.set("status", 1);
        update.set("userId", userId);
        UpdateResult result = mongoTemplate.updateFirst(query, update, KosCoupons.class);
        return result.getModifiedCount() > 0;
    }

    public boolean completeByRedeemCode(String redeemCode, String activityId,String userId, String phone) {
        Query query = new Query(Criteria.where("redeemCode").is(redeemCode));
        Update update = new Update();
        update.set("status", 2);
        update.set("activityId", activityId);
        update.set("phone", phone);
        update.set("userId", userId);
        UpdateResult result = mongoTemplate.updateFirst(query, update, KosCoupons.class);
        return result.getModifiedCount() > 0;
    }

    public boolean releaseByRedeemCode(String redeemCode) {
        Query query = new Query(Criteria.where("redeemCode").is(redeemCode).and("status").is(1));
        Update update = new Update();
        update.set("status", 0);
        update.set("userId", null);
        UpdateResult result = mongoTemplate.updateFirst(query, update, KosCoupons.class);
        return result.getModifiedCount() > 0;
    }
}
